package com.hifar.test.unitclassify.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.hifar.log.AutoLogUtils;
import com.hifar.test.unit.pojo.HfPrjUnitBase;
import com.hifar.test.unit.service.IHfPrjUnitBaseService;
import com.hifar.test.unitclassify.pojo.HfPrjUnitClassify;
import com.hifar.test.unitclassify.pojo.HfPrjUnitClassifyAndUnitVo;
import com.hifar.test.unitclassify.pojo.VO.HfPrjUnitClassifyVO;
import com.hifar.test.unitclassify.service.IHfPrjUnitClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.MultiTableSearchUtils;
import com.hifar.common.SearchCondition;
import com.hifar.common.SearchParamBean;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.PageResult;
import com.hifar.sys.RequestConver;
import com.hifar.sys.SystemLoginUser;
import com.hifar.sys.SystemUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 项目-检测项目-分类 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-03 18:06:03
 */
@RestController
@RequestMapping("/api/busi/test/hfPrjUnitClassifyController")
@Api(tags = "项目-检测项目-分类功能")
public class HfPrjUnitClassifyController {

    @Autowired
    private IHfPrjUnitClassifyService hfPrjUnitClassifyService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private AutoLogUtils autoLogUtils;

    @Autowired
    private IHfPrjUnitBaseService hfPrjUnitBaseService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitClassify> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfPrjUnitClassify> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfPrjUnitClassify> page1 = hfPrjUnitClassifyService.page(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listPage")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPage(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);

        SearchParamBean queryInfo = new SearchParamBean();
        SearchCondition obj = new SearchCondition("secret_level", " in", SystemLoginUser.dataSecretSet);
        queryInfo.getConditionList().add(obj);

        obj = new SearchCondition("del_flag", "!=", "1");
        queryInfo.getConditionList().add(obj);

        queryInfo.getOrderStringList().add("create_time desc");
        MultiTableSearchUtils.getQueryInfo(queryInfo, pageInfo);

        Page<Map<String, Object>> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));

        Page<Map<String, Object>> page1 = hfPrjUnitClassifyService.selectTestMethod(page, " 1=1  " + queryInfo.getWhereSql() + queryInfo.getOrderSql());

        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, page1);
        return BusiResponse.OK(pageResult);

    }


    @PostMapping(value = "/listPage2")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPage2(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitClassify> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<Map<String, Object>> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<Map<String, Object>> page1 = hfPrjUnitClassifyService.selectTestQueryWrapper(page, queryWrapper);
            page1.getRecords().forEach(item -> {
            });
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listPage3")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPage3(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitClassify> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfPrjUnitClassify> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfPrjUnitClassify> page1 = hfPrjUnitClassifyService.selectTestQueryWrapperObj(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listPage4")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPage4(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitClassify> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.like("x.id_name", "张");
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfPrjUnitClassify> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfPrjUnitClassify> page1 = hfPrjUnitClassifyService.selectTestQueryWrapperObj4(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listPage5")
    @ApiOperation(value = "项目-检测项目-分类功能:分页查询列表")
    public BusiResponse listPage5(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfPrjUnitClassifyVO> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfPrjUnitClassifyVO> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfPrjUnitClassifyVO> page1 = hfPrjUnitClassifyService.selectTestQueryWrapperObj5(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "项目-检测项目-分类功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<HfPrjUnitClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag", "1");
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<HfPrjUnitClassify> list = hfPrjUnitClassifyService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.OK(new ArrayList<HfPrjUnitClassify>());
        }
    }


    @PostMapping(value = "/listAllClassifyAndUnitBase")
    @ApiOperation(value = "项目-检测项目-分类功能:查询列表(不带分页)")
    public BusiResponse listAllClassifyAndUnitBase(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        String keyword = StringUtils.trimNull(pageInfo.get("keyword"));
        QueryWrapper<HfPrjUnitClassifyAndUnitVo> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("name", keyword);
        }
        queryWrapper.orderByAsc("row_sort");
        List<HfPrjUnitClassifyAndUnitVo> list = hfPrjUnitClassifyService.listHfPrjUnitClassifyAndUnitVo(queryWrapper);
        return BusiResponse.OK(list);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "项目-检测项目-分类功能:新增")
    public BusiResponse add(@RequestBody HfPrjUnitClassify hfPrjUnitClassify) {
        hfPrjUnitClassify.setPid("0");

        hfPrjUnitClassify.setUpdateUserId(SystemLoginUser.userId);
        hfPrjUnitClassify.setUpdateUserName(SystemLoginUser.idName);
        hfPrjUnitClassify.setUpdateTime(new Date());
        hfPrjUnitClassifyService.save(hfPrjUnitClassify);

        String classifyName = hfPrjUnitClassify.getClassifyName();

        autoLogUtils.addLog("环境试验-试验项目", String.format("新增项目分类:【%s】", classifyName));
        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "项目-检测项目-分类功能:编辑")
    public BusiResponse edit(@RequestBody HfPrjUnitClassify hfPrjUnitClassify) {
        hfPrjUnitClassify.setPid("0");
        hfPrjUnitClassify.setUpdateUserId(SystemLoginUser.userId);
        hfPrjUnitClassify.setUpdateUserName(SystemLoginUser.idName);
        hfPrjUnitClassify.setUpdateTime(new Date());
        hfPrjUnitClassifyService.updateById(hfPrjUnitClassify);

        String classifyName = hfPrjUnitClassify.getClassifyName();
        autoLogUtils.modifyLog("环境试验-试验项目", String.format("编辑项目分类:【%s】", classifyName));

        return BusiResponse.ok("编辑成功！");
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "项目-检测项目-分类功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(value = "id") String id) {
        HfPrjUnitClassify byId = hfPrjUnitClassifyService.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "项目-检测项目-分类功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        //如果分类下有项目则不允许删除

        for (String id : idList) {
            //判断编号是否重复add
            QueryWrapper<HfPrjUnitBase> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().ne(HfPrjUnitBase::getDelFlag, 1);
            queryWrapper.eq("classify_id", id);
            List<HfPrjUnitBase> dataList = hfPrjUnitBaseService.list(queryWrapper);
            if (dataList != null && dataList.size() > 0) {
                return BusiResponse.error(400, String.format("分类[%s]下存在项目信息,无法删除,请先删除分类下的项目！", dataList.get(0).getClassifyName()));
            }
        }
        List<HfPrjUnitClassify> classifiesList = hfPrjUnitClassifyService.listByIds(idList);
        UpdateWrapper<HfPrjUnitClassify> delete = new UpdateWrapper<>();
        delete.in("id", idList);
        delete.set("del_flag", "1");
        hfPrjUnitClassifyService.update(delete);

        String classifyNames = classifiesList.stream()
                .map(HfPrjUnitClassify::getClassifyName)
                .collect(Collectors.joining(","));

        autoLogUtils.deleteLog("环境试验-试验项目", String.format("删除了项目分类:【%s】", classifyNames));
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "项目-检测项目-分类功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfPrjUnitClassifyService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("项目-检测项目-分类.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            autoLogUtils.exportLog("环境试验-试验项目", "导出试验项目");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "项目-检测项目-分类功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.importLog("环境试验-试验项目", "导入试验项目");
                return hfPrjUnitClassifyService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }


}